import React, { useReducer, useState } from 'react';

//count的初始数据
const initCount = 0;
//count的reducer函数
function countReducer(state, action) {
  const { type, data } = action;
  switch (type) {
    case "incrementCount":
      return state + data;
    case "decrementCount":
      return state - data;
    case "doubleCount":
      return state * 2
  }
}


//userMessage的初始化数据
const initUserMessage = {
  name: "xiaowang",
  age: 18,
  height: 180
}

//userMessage的reducer函数
function userMessageReducer(state, { type, data }) {
  switch (type) {
    case "changeAge":
      return { ...state, age: state.age + 1 }
    case "changeHeight":
      return { ...state, height: state.height + data }
  }
}


export default function App() {
  /* const [count, setCount] = useState(0);
  const incrementCount = () => {
    setCount(x => x + 1)
  }
  const decrementCount = () => {
    setCount(x => x - 1)
  }
  const doubleCount = () => {
    setCount(x => 2 * x)
  } */

  const [count, dispatchCount] = useReducer(countReducer, initCount)
  const [userMessage, dispatchUserMessage] = useReducer(userMessageReducer, initUserMessage)

  /* const [userMessage, setUserMessage] = useState({
    name: "xiaowang",
    age: 18,
    height: 180
  })


  const changeAge = () => {
    setUserMessage({ ...userMessage, age: userMessage.age + 1 })
  }
  const changeHeight = () => {
    setUserMessage({ ...userMessage, height: userMessage.height + 1 })
  } */
  return (
    <div>
      <h1>App:{count}</h1>
      <button onClick={() => {
        dispatchCount({ type: "incrementCount", data: 1 })
      }}>累加count</button>
      <button onClick={() => {
        dispatchCount({ type: "decrementCount", data: 1 })
      }}>累减count</button>
      <button onClick={() => {
        dispatchCount({ type: "doubleCount" })
      }}>双倍count</button>

      <h1>UserName:{userMessage.name}---userAge:{userMessage.age}---userHeight:{userMessage.height}</h1>
      <button onClick={() => {
        dispatchUserMessage({ type: "changeAge" })
      }}>改变年龄</button>
      <button onClick={() => {
        dispatchUserMessage({ type: "changeHeight", data: 2 })
      }}>改变身高</button>
    </div>
  )
}
